package jsyf.oa.web.until;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * Created by Administrator on 2018/6/26 0026.
 */
public class WordDocExport {
    private static Configuration configuration = null;
    private static Map<String, Template> allTemplate = null;

    public static void fileDoc(String buyType, String contractType) {
        configuration = new Configuration(Configuration.VERSION_2_3_0);
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassicCompatible(true);
        configuration.setClassForTemplateLoading(WordDocExport.class, "/contract");
        allTemplate = new HashMap<String, Template>();
        try {
            if ("1".equalsIgnoreCase(contractType)) {
                if ("全款".equals(buyType)) {
                    allTemplate.put("fullPayment", configuration.getTemplate("fullPayment.ftl"));
                } else if ("内部分期".equals(buyType)) {
                    allTemplate.put("installPayment", configuration.getTemplate("installPayment.ftl"));
                } else if ("融资租赁".equals(buyType)) {
                    allTemplate.put("financingPayment", configuration.getTemplate("financingPayment.ftl"));
                } else {
                    allTemplate.put("financBaoPayment", configuration.getTemplate("financBaoPayment.ftl"));
                }
            } else {
                allTemplate.put("oldPayment", configuration.getTemplate("oldPayment.ftl"));
            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    private WordDocExport() {
    }

    public static File createDoc(Map<?, ?> dataMap, String type) {
        String name = "导出的合同" + (int) (Math.random() * 100000) + ".doc";
        File f = new File(name);
        Template t = allTemplate.get(type);
        try {
            //这个地方不能使用FileWriter因为需要指定编码类型否则声场的word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return f;
    }
}
